package com.jiguang.shangcheng.servlet;

import com.jiguang.shangcheng.dao.ShangChengDao;
import com.jiguang.shangcheng.pojo.User;
import com.jiguang.shangcheng.utils.MD5;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/shang/register")
public class register extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");

        //获取数据
        String number = req.getParameter("number");
        String pwd = req.getParameter("pwd");
        String netname = req.getParameter("netname");

        //判断数据是否完整
        if(number == null || number.equals("") || pwd == null || pwd.equals("") || netname == null || netname.equals("")){
            PrintWriter out = resp.getWriter();
            out.println("<script>alert('请填写完整信息');location.href='/shang/register.jsp';</script>");
            out.close();
            return;
        }

        //判断number是否重复
        ShangChengDao shangChengDao = new ShangChengDao();
        boolean isTure = shangChengDao.selectNumber(number);
        if (isTure){
            //重复
            PrintWriter out = resp.getWriter();
            out.println("<script>alert('账号已存在');location.href='/shang/register.jsp';</script>");
            out.close();
            return;
        }else{
            //不重复，注册账号
            User user = new User();
            user.setPassword(MD5.md5(pwd));
            System.out.println(MD5.md5(pwd));
            user.setNumber(number);
            user.setNetname(netname);
            //默认头像
            user.setPhoto("4bd4638e-192c-47b7-8734-5bdc5e753214/name.png");
            boolean result = shangChengDao.insertNumber(user);
            if(!result){
                PrintWriter out = resp.getWriter();
                out.println("<script>alert('注册失败');location.href='/shang/register.jsp';</script>");
                out.close();
            }else{
                PrintWriter out = resp.getWriter();
                out.println("<script>alert('注册成功,等待管理员确认');location.href='/shang/login.jsp';</script>");
                out.close();
            }
        }
    }
}
